package spitfire.ksim.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import spitfire.ksim.algorithm.FuzzyDBUpdatedListener;
import spitfire.ksim.algorithm.FuzzyEntry;
import spitfire.ksim.algorithm.FuzzyRuleBase;

/**
 * @author Adam
 * 
 */
public class KFuzzyDBPanel extends JPanel {
	private static final long serialVersionUID = 6152591797454248325L;
	private FuzzyRuleBase fuzzyDB;
	private JComboBox comboBoxEntry = new JComboBox();
	private KFuzzyRulePanel rulePanel = new KFuzzyRulePanel();

	public KFuzzyDBPanel(FuzzyRuleBase ruleBase) {
		super();
		this.fuzzyDB = ruleBase;
		this.setLayout(new BorderLayout());
		this.add(rulePanel, BorderLayout.CENTER);
		this.add(comboBoxEntry, BorderLayout.NORTH);
		comboBoxEntry.setPreferredSize(new Dimension(300, 22));
		comboBoxEntry.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == ItemEvent.SELECTED) {
					Object entry = comboBoxEntry.getSelectedItem();
					if (entry instanceof FuzzyEntry) {
						rulePanel.setFuzzyRule(((FuzzyEntry) entry).getRule());
						repaint();
					}
				}
			}
		});
		for (FuzzyEntry entry : fuzzyDB.getFuzzyEntryList()) {
			comboBoxEntry.addItem(entry);
		}
		
		fuzzyDB.addFuzzyDBUpdatedListener(new FuzzyDBUpdatedListener() {
			@Override
			public void fuzzyDBUpdated() {
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						Object selection = comboBoxEntry.getSelectedItem();
						comboBoxEntry.removeAllItems();
						for (FuzzyEntry entry : fuzzyDB.getFuzzyEntryList()) {
							comboBoxEntry.addItem(entry);
						}
						if (selection != null) {
							comboBoxEntry.setSelectedItem(selection);
						}
					}
				});
			}
		});
	}
}
